package com.itheima.shop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itheima.shop.dto.UserMessage;
import com.itheima.shop.entity.User;
import com.itheima.shop.mapper.UserMapper;
import com.itheima.shop.service.UserService;
import com.itheima.shop.util.BeanCopyUtil;
import com.itheima.shop.util.MailEyouUtil;
import com.itheima.shop.util.Md5Util;
import com.itheima.shop.util.UuidUtil;

@Service
public class UserServiceImp implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserMessage Login(String username, String password) {
		// TODO Auto-generated method stub
		User user = this.userMapper.findByUsername(username);
		UserMessage userMsg = new UserMessage();
		BeanCopyUtil.beanCopy(user, userMsg);
		if (user == null) {
			userMsg.setMsgCode(1002);
		} else if (user.getPassword().equals(Md5Util.encodeByMd5(password)) && user.getState() == 1) {
			userMsg.setMsgCode(1001);
		} else if (!user.getPassword().equals(Md5Util.encodeByMd5(password))) {
			userMsg.setMsgCode(1002);
		} else if (user.getState() == 0) {
			userMsg.setMsgCode(1003);
		}
		return userMsg;
	}

	@Override
	public User checkUsername(String username) {
		return userMapper.findByUsername(username);
	}

	@Override
	public UserMessage register(User user) {
		User checkUser = checkUsername(user.getUsername());
		UserMessage userMsg = new UserMessage();
		if(checkUser!=null) {
			BeanCopyUtil.beanCopy(checkUser, userMsg);
			userMsg.setMsgCode(2003);
			return userMsg;
		}
		
		// 设置未激活
		user.setState(0);
		user.setPassword(Md5Util.encodeByMd5(user.getPassword()));
		user.setCode(UuidUtil.getUuid());
		int result = userMapper.insert(user);
		System.out.println(user);
		BeanCopyUtil.beanCopy(user, userMsg);
		// 如果插入成功，發送激活邮件
		if (result > 0) {
			// 此处有隐患 todo
			String emailMsg = "<h3>" + user.getName()
					+ ",恭喜您，注册成功！请您尽快<a href='http://127.0.0.1:8080/heima-shop-ssm/user/activate?code=" + user.getCode()
					+ "'>激活</a></h3>";
			MailEyouUtil.sendMail(MailEyouUtil.FROM_ADMIN_EMAIL, user.getEmail(), "黑马商城激活邮件",
					emailMsg);
			userMsg.setMsgCode(2001);
		} else {
			userMsg.setMsgCode(2099);
		}
		return userMsg;
	}

	@Override
	public UserMessage activate(String code) {
		int result = userMapper.activate(code);
		UserMessage userMsg  = new UserMessage();
		if(result>0) {
			userMsg.setMsgCode(2002);
		} else {
			userMsg.setMsgCode(2004);
		}
		return userMsg;
//		return "激活成功";
	}

}
